﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using Webcar.Utils;
namespace Webcar.BLL
{
    public static class FileUploadHelper
    {
        public static string GetContentType(string fileName)
        {

            string contentType = "application/octet-stream";

            string ext = System.IO.Path.GetExtension(fileName).ToLower();

            Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

            if (registryKey != null && registryKey.GetValue("Content Type") != null)

                contentType = registryKey.GetValue("Content Type").ToString();

            return contentType;

        }
        public static string UploadFile(this HttpFileCollectionBase files)
        {
            string ext = "rar|zip|doc|xls|ppt|docx|";
            return files.Upload("files",ext);
        }
        //public static string UploadWorkFile(this HttpFileCollectionBase files)
        //{
        //    if (files.IsEmpty()) return null;
        //    string ext = "jpg|jpeg|gif|bmp|";
        //    string filename = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(files[0].FileName).ToLower();
        //    return files.Upload("files", ext,filename);
        //}
        public static bool IsEmpty(this HttpFileCollectionBase files,int index=0)
        {
            if (files.Count <index+1) return true;
            if (files[index].FileName.IsNull()) return true;
            return false;
        }

        public static string UploadImage(this HttpFileCollectionBase files,string phototype,int w=320,int h=240,string mode="H",int file_index=0)
        {
            if (files.IsEmpty()) return null;
            var file = files[file_index];
            string ext = "jpg|jpeg|gif|bmp|";
            string filename = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName).ToLower();
                
            string large_image_folder = @"photo\"+phototype+@"\large";
            string small_image_folder = @"photo\"+phototype+@"\small";

            files.Upload(large_image_folder, ext, filename, file_index);

            //保存缩略图
            string large_file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(large_image_folder, filename));
            string small_file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(small_image_folder, filename));
            
            if (Directory.Exists(Path.GetDirectoryName(small_file)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(small_file));
            }

            MakeThumbnail(large_file, small_file, w, h, mode);
            return filename;

        }
        public static string UploadGsFile(this HttpFileCollectionBase files)
        {
            string ext = "rar|zip|doc|xls|ppt|docx|";
            return files.Upload("gs_file", ext);
        }

        public static string Upload(this HttpFileCollectionBase files,string save_dir,string ext,string new_filename=null,int file_index=0)
        {
            if (files.IsEmpty()) return null;
            var file = files[file_index];
            if (file.ContentLength == 0) return null;
            
            string fileext = Path.GetExtension(file.FileName).ToLower();
            if (ext.IndexOf(fileext.Substring(fileext.LastIndexOf(".") + 1)) < 0)
            {
                throw new Exception("该格式的附件不能上传。");
            }

            //string path = Path.Combine( AppDomain.CurrentDomain.BaseDirectory ,save_dir);
            if (new_filename == null)
            {
                new_filename = Path.GetFileName(file.FileName);
            }
            
            save_dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, save_dir);
            if (Directory.Exists(save_dir) == false)
            {
                Directory.CreateDirectory(save_dir);
            }
            //string filename = Path.GetFileName(file.FileName);
            file.SaveAs(Path.Combine(save_dir, new_filename));
            

            return new_filename;
        }


        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    }
}